package com.pat.java.base.http;

import java.net.*;
import java.io.*;

public class Search {
	public static void main(String args[]) {
//		String fullURL = "http://bingle.pku.edu.cn/scripts/ftp_search.exe?";
		String fullURL = "http://www.baidu.com";

		InputStream theData = null;
		URL u = null;
		
		//建立URL对象，参数为请求地址+编码后的请求串
		try {
//			fullURL += URLEncoder.encode("cdtype", "UTF-8") + "="
//					+ URLEncoder.encode("GB", "UTF-8");
//			fullURL += "&" + URLEncoder.encode("word", "UTF-8") + "="
//					+ URLEncoder.encode("Java", "UTF-8");
			u = new URL(fullURL);
			
			//打开连接，读入流数据
			URLConnection conn = u.openConnection();
			conn.connect();
			theData = conn.getInputStream();
			
			//得到网页类型：text/html
			String contentType = conn.getContentType();
			System.out.println("contentType--->"+contentType);
			
			//建立文件对象和读取的流对象
			File f = new File("files/result.html");
			FileOutputStream fOut = new FileOutputStream(f);
			PrintWriter p = new PrintWriter(fOut);
			if (contentType.toLowerCase().startsWith("text")) {
				BufferedReader in = new BufferedReader(new InputStreamReader(
						theData));
				String line;
				while ((line = in.readLine()) != null) {
					//输出到文件
					p.println(line);
					System.out.println("line---->"+line);
				}
				p.flush();
				p.close();
				fOut.close();
			} else {
				System.out.println("程序只处理文本响应。");
				System.out.println("得到的类型为："+contentType);
			}
		}catch (UnsupportedEncodingException e) {
			System.err.println(e);
		} catch (MalformedURLException e) {
			System.err.println("网页错误:" + fullURL + "" + e);
			System.exit(1);
		} catch (IOException e) {
			System.err.println(e);
			System.exit(2);
		}
	}
}
